<template>
  <view class="location-picker-page">
    <!-- 自定义导航栏 -->
    <qmy-custom-navbar :title="'选择位置'" :showBack="true" @back="goBack">
      <template #right>
        <text class="nav-cancel" @click="goBack">取消</text>
      </template>
    </qmy-custom-navbar>
    
    <!-- 地图选择器 -->
    <view class="map-picker-container" :style="{paddingTop: menuObject.top + menuObject.height + 'px'}">
      <amap-location-picker 
        :initialLocation="initialLocation"
        @confirm="onLocationConfirm"
      />
    </view>
  </view>
</template>

<script>
import AmapLocationPicker from '@/components/amap-location-picker/amap-location-picker.vue'

export default {
  components: {
    AmapLocationPicker
  },
  data() {
    return {
      // #ifdef MP-WEIXIN
      menuObject: uni.getMenuButtonBoundingClientRect(),
      // #endif
      // #ifndef MP-WEIXIN
      menuObject: { top: 0, height: 44 },
      // #endif
      initialLocation: {
        latitude: 0,
        longitude: 0,
        name: '',
        address: ''
      }
    }
  },
  onLoad(options) {
    console.log('地图选择页面接收到的参数:', options);
    
    // 获取传递的初始位置信息
    if (options.latitude && options.longitude) {
      this.initialLocation = {
        latitude: parseFloat(options.latitude) || 0,
        longitude: parseFloat(options.longitude) || 0,
        name: decodeURIComponent(options.name || ''),
        address: decodeURIComponent(options.address || '')
      }
      console.log('解析后的初始位置:', this.initialLocation);
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 确认位置选择
    onLocationConfirm(location) {
      console.log('确认选择位置:', location);
      
      try {
        // 方式1: 通过事件通道返回选择的位置信息（推荐方式）
        const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
        if (eventChannel && eventChannel.emit) {
          console.log('通过事件通道发送位置信息');
          eventChannel.emit('locationSelected', location);
        }
        
        // 方式2: 通过全局事件（备用方式）
        uni.$emit('locationSelected', location);
        
        // 方式3: 存储到本地缓存（兜底方案）
        uni.setStorageSync('selectedLocation', JSON.stringify(location));
        
      } catch (error) {
        console.error('发送位置信息失败:', error);
        // 如果所有方式都失败，至少保存到缓存
        try {
          uni.setStorageSync('selectedLocation', JSON.stringify(location));
        } catch (e) {
          console.error('保存到缓存也失败:', e);
        }
      }
      
      // 返回上一页
      uni.navigateBack({
        success: () => {
          console.log('成功返回上一页');
        },
        fail: (err) => {
          console.error('返回上一页失败:', err);
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.location-picker-page {
  width: 100%;
  height: 100vh;
  
  .nav-cancel {
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 20rpx;
  }
  
  .map-picker-container {
    width: 100%;
    height: calc(100vh - var(--window-top));
  }
}
</style> 